<template>
    <div class="supplier-quotation-container">
        <!-- 头部信息 -->
        <div class="header">
            <div class="supplier-info" v-if="currentSupplier.suppliers">
                <span>供货商：{{ currentSupplier.suppliers.name || '--' }}</span>
                <span>联系人：{{ formatContactInfo(currentSupplier.suppliers) }}</span>
            </div>
        </div>

        <!-- 查询条件 -->
        <div class="query-form">
            <el-form :inline="true" :model="formInline">
                <el-form-item label="商品名称">
                    <el-input
                        v-model="formInline.searchProductName"
                        placeholder="请输入商品名称"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="类别">
                    <el-select
                        v-model="formInline.searchProductCategory"
                        placeholder="请选择类别"
                        clearable
                    >
                        <el-option
                            v-for="item in productCategory"
                            :key="item.id"
                            :label="item.categoryName"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="报价状态">
                    <el-select
                        v-model="formInline.searchStatus"
                        placeholder="请选择报价状态"
                        clearable
                    >
                        <el-option label="全部" value="" />
                        <el-option label="通过" value="1" />
                        <el-option label="不通过" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 报价列表 -->
        <div class="table-container">
            <el-table
                :data="quotationList"
                border
                style="width: 100%"
                v-loading="loading"
            >
                <el-table-column
                    prop="productId"
                    label="商品编号"
                    width="180"
                    align="center"
                />
                <el-table-column
                    label="商品名称"
                    width="180"
                    align="center"
                >
                    <template v-slot="{row}">
                        <span class="product-name">{{ getProductName(row) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="当前报价"
                    width="150"
                    sortable
                    align="center"
                >
                    <template v-slot="{row}">
                        <span class="price-tag">{{ formatPrice(row.productOffer) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="商品分类"
                    width="180"
                    align="center"
                >
                    <template v-slot="{row}">
                        <el-tag type="info" size="small">{{ getCategoryName(row) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="报价状态"
                    width="120"
                    align="center"
                >
                    <template v-slot="{row}">
                        <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                            {{ row.status === '1' ? '通过' : '不通过' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="180"
                    align="center"
                >
                    <template v-slot="{row}">
                        <el-button
                            type="primary"
                            size="small"
                            @click="showEditDialog(row)"
                            class="action-btn"
                        >
                            <i class="el-icon-edit"></i> 修改
                        </el-button>
                        <el-button
                            type="danger"
                            size="small"
                            @click="handleCancel(row)"
                            class="action-btn"
                        >
                            <i class="el-icon-delete"></i> 取消
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                    :current-page="current"
                    :page-sizes="pageList"
                    :page-size="pageSize"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                />
            </div>
        </div>

        <!-- 修改报价对话框 -->
        <el-dialog
            title="修改报价"
            :visible.sync="editDialogVisible"
            width="500px"
            @closed="handleDialogClose"
        >
            <el-form
                :model="editForm"
                :rules="editRules"
                ref="editFormRef"
                label-width="100px"
            >
                <el-form-item label="商品名称">
                    <span>{{ editForm.productName }}</span>
                </el-form-item>
                <el-form-item label="商品分类">
                    <span>{{ editForm.categoryName }}</span>
                </el-form-item>
                <el-form-item label="当前报价" prop="productOffer">
                    <el-input-number
                        v-model="editForm.productOffer"
                        :min="0"
                        :precision="2"
                        :step="0.1"
                        controls-position="right"
                        @change="handlePriceChange"
                    />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'SuppliersMaintenance',
    data() {
        return {
            // 查询条件
            formInline: {
                searchProductName: '',
                searchProductCategory: '',
                searchStatus: ''
            },
            // 供应商信息
            currentSupplier: { suppliers: null },
            // 商品分类列表
            productCategory: [],
            // 分页相关
            vo: {},
            current: 1,
            pageSize: 10,
            pageList: [10, 15, 20, 30],
            total: 0,
            // 报价列表
            quotationList: [],
            // 加载状态
            loading: false,
            // 编辑对话框相关
            editDialogVisible: false,
            editForm: {
                id: '',
                productName: '',
                categoryName: '',
                productOffer: 0,
            },
            editRules: {
                productOffer: [
                    { required: true, message: '请输入报价金额', trigger: 'blur' },
                    { type: 'number', min: 0, message: '报价不能为负数', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择报价状态', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.initData()
    },
    methods: {
        // 新增价格变化处理
        handlePriceChange(value) {
            // 强制保留两位小数
            this.editForm.productOffer = parseFloat(value.toFixed(2))
        },
        // 初始化数据
        async initData() {
            try {
                this.loading = true
                await Promise.all([
                    this.loadSupplierInfo(),
                    this.loadCategories(),
                    this.getQuotationList()
                ])
            } catch (error) {
                console.error('初始化数据失败:', error)
                this.$message.error('数据加载失败，请稍后重试')
            } finally {
                this.loading = false
            }
        },

        // 加载供货商信息
        async loadSupplierInfo() {
            try {
                const user = JSON.parse(sessionStorage.getItem('user')) || {}
                const { data } = await this.$axios.post(`login/selectIdSuppliers/${user.id}`)
                this.currentSupplier = data || { suppliers: null }
            } catch (error) {
                console.error('加载供应商信息失败:', error)
                this.$message.error('加载供应商信息失败')
            }
        },

        // 加载商品分类
        async loadCategories() {
            try {
                const { data } = await this.$axios.post(`productCategory/listProductCategory`)
                this.productCategory = data || []
            } catch (error) {
                console.error('加载商品分类失败:', error)
                this.$message.error('加载商品分类失败')
            }
        },

        // 获取报价列表
        async getQuotationList() {
            try {
                this.loading = true
                const user = JSON.parse(sessionStorage.getItem('user')) || {}
                this.$axios.post(
                    `quotes/queryByProductUserInfo/${this.current}/${this.pageSize}/${user.id}`,
                    this.vo
                ).then(r =>{
                    console.log(333,r.data.list)
                    this.quotationList = r.data?.list || []
                    this.total = r.data?.total || 0
                })

            } catch (error) {
                console.error('获取报价列表失败:', error)
                this.$message.error('获取报价列表失败')
            } finally {
                this.loading = false
            }
        },

        // 查询
        handleQuery() {
            this.current = 1
            this.vo = { ...this.formInline }
            this.getQuotationList()
        },

        // 重置查询
        resetQuery() {
            this.formInline = {
                searchProductName: '',
                searchProductCategory: '',
                searchStatus: ''
            }
            this.handleQuery()
        },

        // 分页大小变化
        handleSizeChange(val) {
            this.pageSize = val
            this.getQuotationList()
        },

        // 页码变化
        handlePageChange(val) {
            this.current = val
            this.getQuotationList()
        },

        // 格式化联系人信息
        formatContactInfo(supplier) {
            if (!supplier) return '--'
            const name = supplier.contactName || '未设置'
            const phone = supplier.contactPhone || '未设置'
            return `${name}/${phone}`
        },

        // 格式化价格
        formatPrice(price) {
            if (price === undefined || price === null) return '--'
            return `¥${parseFloat(price).toFixed(2)}`
        },

        // 获取商品名称
        getProductName(row) {
            return row.products?.[0]?.name || '--'
        },

        // 获取分类名称
        getCategoryName(row) {
            return row.productCategory?.[0]?.categoryName || '--'
        },

        // 显示编辑对话框
        showEditDialog(row) {
            this.editForm = {
                id: row.id,
                productName: this.getProductName(row),
                categoryName: this.getCategoryName(row),
                productOffer: parseFloat(row.productOffer) || 0,
            }
            this.editDialogVisible = true
        },

        // 提交编辑表单
        async submitEditForm() {
            try {
                await this.$refs.editFormRef.validate()

                this.loading = true
                this.$axios.put('quotes/modifQutoe', this.editForm).then(r =>{
                    if (r.data ==='Yes') {
                        this.$message.success('报价更新成功')
                        this.editDialogVisible = false
                        this.getQuotationList()
                    } else {
                        this.$message.error(r?.message || '报价更新失败')
                    }
                })
            } catch (error) {
                console.error('更新报价失败:', error)
                this.$message.error('更新报价失败')
            } finally {
                this.loading = false
            }
        },

        // 对话框关闭处理
        handleDialogClose() {
            this.$refs.editFormRef?.resetFields()
        },

        // 取消报价
        async handleCancel(row) {
            try {
                await this.$confirm('确定要取消该报价吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })

                this.loading = true
                this.$axios.post(`quotes/deleteQuote/${row.id}`).then( r=>{
                    console.log(555,r.data)
                    if (r.data === 'Yes') {
                        this.$message.success('报价取消成功')
                        this.getQuotationList()
                    } else {
                        this.$message.error(r?.message || '报价取消失败')
                    }
                })
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('取消报价失败:', error)
                    this.$message.error('取消报价失败')
                }
            } finally {
                this.loading = false
            }
        }
    }
}
</script>

<style scoped>
.supplier-quotation-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;

        .supplier-info {
            display: flex;
            gap: 20px;
            font-size: 14px;
            color: #666;

            span {
                display: inline-block;
                min-width: 200px;
            }
        }
    }

    .query-form {
        margin-bottom: 20px;
    }

    .table-container {
        margin: 20px 0;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        font-weight: 500;

        ::v-deep .el-table__header th {
            background-color: #f8f9fa;
            color: #495057;
            padding: 12px 0;
        }

        ::v-deep .el-table__body td {
            padding: 10px 0;
            border-bottom: 1px solid #e9ecef;
        }

        ::v-deep .el-table__body tr:hover>td {
            background-color: #f8f9fa !important;
        }

        .product-name {
            color: #333;
            font-weight: 500;
        }

        .price-tag {
            color: #f56c6c;
            font-weight: 500;
        }

        .action-btn {
            padding: 6px 10px;
            margin: 0 3px;
            font-size: 12px;
        }
    }

    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
}

@media (max-width: 768px) {
    .supplier-info {
        flex-direction: column;
        gap: 8px !important;
    }

    .action-btn {
        padding: 5px 8px !important;
        margin: 2px 0 !important;
        display: block;
        width: 100%;

        & + .action-btn {
            margin-top: 5px !important;
        }
    }
}
</style>